
//
//  EmoticonInputView.swift
//
//  Created by yang on 2017/11/12.
//  Copyright © 2017年 成品家（北京）网络科技有限公司. All rights reserved.
//

import UIKit

//全局变量
private let cellID = "cellID"

class EmoticonInputView: UIView {
    
    //定义闭包
    var selectedEmoticonCallBack: ((_ emoticon: YYYEmoticonModel?)->())?
    //九宫格视图
    private lazy var collectionView = UICollectionView(frame:  CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height - 40), collectionViewLayout: EmoticonViewFlowLayout())
    //分页控件
  
    private lazy var pageControl = UIPageControl(number: 1, currentPageColor: UIColor.RGBColor(red: 20, green: 82, blue: 184), pageColor: UIColor.darkGray)
    
    //底部工具栏
    lazy var toolView = EmoticonToolView()
    
    //重载构造函数
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        //初始化控件
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
extension EmoticonInputView
{
    //初始化控件
    func setupUI()
    {
        self.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 258)
        //九宫格
        collectionView.backgroundColor = UIColor.white
        collectionView.showsVerticalScrollIndicator = false
        collectionView.isPagingEnabled = true
        collectionView.bounces = false
        //注册cell
        collectionView.register(EmoticonCollectionViewCell.self, forCellWithReuseIdentifier: cellID)
        //设置数据源
        collectionView.dataSource = self
        //设置代理
        collectionView.delegate = self
        addSubview(collectionView)
        
        //添加分页控件
        pageControl.frame = CGRect(x: 0, y: collectionView.bottom-30, width: kDeviceWidth, height: 30)
        pageControl.center.x = center.x
        addSubview(pageControl)
        
        //设置分页控件图片
        let bundle = EmoticonManager.shared.bundle
        
        
        guard let normalImage = UIImage(named: "compose_keyboard_dot_normal", in: bundle, compatibleWith: nil),
              let selectedImage = UIImage(named: "compose_keyboard_dot_selected", in: bundle, compatibleWith: nil) else
        {
            return
        }
//        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: selectedImage1)
//        pageControl.pageIndicatorTintColor = UIColor(patternImage: normalImage1)
        
        //使用运行时获取控件的成员变量
        print(UIPageControl.cz_ivarsList())
        //使用KVC设置私有变量属性
        pageControl.setValue(normalImage, forKey: "_pageImage")
        pageControl.setValue(selectedImage, forKey: "_currentPageImage")
        
        //底部工具栏
        addSubview(toolView)
        //设置工具栏代理
        toolView.delegate = self
    }
}

//底部工具栏的代理方法
extension EmoticonInputView: EmoticonToolViewDelegate
{
    func emoticonToolViewDidSelectedItemIndex(toolView: EmoticonToolView, index: Int)
    {
        //让UICollectionView发生滚动
        let indexPath = IndexPath(item: 0, section: index)
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
        toolView.selectedIndex = index
    }
}

//UICollectionView数据源方法
extension EmoticonInputView: UICollectionViewDataSource, UICollectionViewDelegate
{
    //组数
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return EmoticonManager.shared.packages.count
    }
    //每组中的item数量
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        let itemCount = EmoticonManager.shared.packages[section].numberOfPages
        return itemCount
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
    {
        //取cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! EmoticonCollectionViewCell
        cell.emoticons = EmoticonManager.shared.packages[indexPath.section].emoticon(page: indexPath.item)
        //设置代理
        cell.delegate = self
        //返回cell
        return cell
    }
    
    //滑动代理
    func scrollViewDidScroll(_ scrollView: UIScrollView)
    {
        //获取中心点
        var center = scrollView.center
        center.x += scrollView.contentOffset.x
        //获取可见的items的indexPath
        let indexPaths = collectionView.indexPathsForVisibleItems
        //定义目标indexPath
        var targetIndexPath: IndexPath?
        //获取对应位置的cell
        for indexPath in indexPaths
        {
            let cell = collectionView.cellForItem(at: indexPath)
            if cell?.frame.contains(center) == true
            {
                targetIndexPath = indexPath
                break
            }
        }
        guard let target = targetIndexPath else
        {
            return
        }
        toolView.selectedIndex = target.section
        
        //设置分页控件
        pageControl.numberOfPages = collectionView.numberOfItems(inSection: target.section)
        pageControl.currentPage = target.item
    }
}

extension EmoticonInputView: EmoticonCellDelegate
{
    func emoticonCellDidSelectedEmoticon(cell: EmoticonCollectionViewCell, em: YYYEmoticonModel?)
    {
        selectedEmoticonCallBack?(em)
        //添加最近使用的表情
        guard let em = em else
        {
            return
        }
        EmoticonManager.shared.addRecentEmoticons(em: em)
        
        //判断如果是最近分组，不进行刷新操作
        let indexPaths = collectionView.indexPathsForVisibleItems
        if indexPaths[0].section == 0
        {
            return
        }
        //刷新第0个分组
        var indexSet = IndexSet()
        indexSet.insert(0)
        collectionView.reloadSections(indexSet)
    }
}
